import { LXClickData, LXViewData, CacheItem, Cache } from './types';
import { getURLPath } from './tools';

const cache: Cache = {};

export function getCache(key: string): LXClickData | LXViewData | null {
  const item: CacheItem | undefined = cache[key];
  if (item) {
    return item.data;
  }
  return null;
}

export function setCache(key: string, data: object): void {
  cache[key] = { url: getURLPath(), data };
}

export function clearOtherPagesCache() {
  const pageUrl: string = getURLPath();
  Object.keys(cache).forEach((key: string) => {
    const { url, data: { config } } = cache[key];
    if (url !== pageUrl) {
      if (config.count) config.count = 0;
      if (config.startTime) config.startTime = 0;
      delete cache[key];
    }
  });
}
